# from rest_framework_jwt.views import obtain_jwt_token
import json
import requests
from requests.adapters import HTTPAdapter


class ZabbixAlarmClient(object):
    def __init__(self):
        self.url = 'http://127.0.0.1:18080/'
        self.timeout = 20
        self.user = {"username": "devadmin", "password": "OHuHsmw8!7^#j71$"}
        # 获得鉴权数据
        self.s = requests.Session()
        self.s.mount('http://', HTTPAdapter(max_retries=3))
        self.s.mount('https://', HTTPAdapter(max_retries=3))
        # print(self.reqmfa())

        self.token = "JWT " + self.get_token()

        self.headers = {"Authorization": self.token,
                        "content-type": "application/json"}

    def get_token(self):
        token_url = self.url + 'api-token-auth/'
        headers = {"content-type": "application/json"}
        token_req = requests.post(
            token_url, data=json.dumps(self.user), headers=headers)
        token = token_req.json().get('token')
        return token

    def post_alarm_types(self, data):
        res = self.s.post(self.url + 'monitor/alarm_types/', data=json.dumps(data),
                          headers={"content-type": "application/json", "Authorization": self.token})
        # res.content返回的是bytes，转换成字符串后再转成json
        rdata = json.loads(str(res.content, 'utf-8'))
        return rdata
